/*
* Copyright (C) 2024, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: iaom <zhangpengfei@kylinos.cn>
 *
 */

#include "widgets-browser-model.h"

#include <QMetaEnum>
#include <widget-loader.h>

WidgetsBrowserModel::WidgetsBrowserModel(QObject* parent) : QAbstractListModel(parent)
{
    m_widgetLoader = new UkuiQuick::WidgetLoader(this);
    m_widgets = m_widgetLoader->widgetsMetadata();
}

int WidgetsBrowserModel::rowCount(const QModelIndex& parent) const
{
    return m_widgets.count();
}

int WidgetsBrowserModel::columnCount(const QModelIndex& parent) const
{
    return 1;
}

QVariant WidgetsBrowserModel::data(const QModelIndex& index, int role) const
{
    if (!checkIndex(index, CheckIndexOption::IndexIsValid)) {
        return {};
    }
    switch (role) {
        case Thumbnail:
            return "image://theme/" + m_widgets.at(index.row()).thumbnail();
        case Name:
            return m_widgets.at(index.row()).name();
        case Id:
            return m_widgets.at(index.row()).id();
        default: ;
    }

    return {};
}

QHash<int, QByteArray> WidgetsBrowserModel::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
    const QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("WidgetMetadata"));

    for (int i = 0; i < e.keyCount(); ++i) {
        roles.insert(e.value(i), e.key(i));
    }
    return roles;
}
